import * as vscode from "vscode";
import { getPackageJson } from "@ap/util/packageJson";
import { auth } from "@ap/util/request";
import { showErrorMessage } from "@ap/util/vscode/message";
import { arenaErrorMsg } from "@ap/util/vscode/errorMsg";
import path from "path";
import { $context } from "@ap/extension";
import { PackageConfig } from "@ap/types/config";
export default function box3ModelView(modelId: string, label: string) {
  getPackageJson<PackageConfig>("map")
    .then((packageJson) => {
      if (packageJson?.id && auth && packageJson?.id.length > 0) {
        const id = encodeHTML(packageJson.id);
        const authEncoded = encodeHTML(auth);
        createWebviewPanel(id, modelId, authEncoded, label);
      } else {
        showErrorMessage(
          arenaErrorMsg.LOG_IN_AND_CONFIGURE_MAP_EDITHASH_CORRECTLY,
        );
      }
    })
    .catch((error) => {
      showErrorMessage(
        arenaErrorMsg.INITIALIZATION_FAILED_TRY_TO_REOPEN_THE_PLUG_IN,
      );
    });
}

function createWebviewPanel(
  mapId: string,
  modelId: string,
  authEncoded: string,
  label: string,
) {
  const web = vscode.window.createWebviewPanel(
    "arenaPro",
    label ?? "模型创作端",
    vscode.ViewColumn.Active,
    { enableScripts: true, retainContextWhenHidden: true },
  );
  web.webview.html = getWebviewContent(mapId, modelId, authEncoded);
  web.iconPath = vscode.Uri.file(
    path.join($context.extensionPath, "image", "arena.svg"),
  );
}
function getWebviewContent(mapId: string, modelId: string, auth: string) {
  return `
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <style>
        body {
            padding: 0 0px!important;
        }
    </style>
</head>
<body>
<iframe id="box3iframe" name="box3iframe" height="100%" width="100%" src="https://voxa.dao3.fun/?parentType=engine&modelId=${modelId}&mapId=${mapId}&token=${auth}" scrolling="auto" frameborder="0" allow="geolocation; microphone; camera; clipboard-read; clipboard-write; pointerlock" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-pointer-lock allow-downloads"></iframe>
<script>
    var box3iframe = document.getElementById("box3iframe"); 
    function changeFrameHeightAndWidth() { 
        box3iframe.height = document.documentElement.clientHeight;
        box3iframe.width = document.documentElement.clientWidth;
    }
    changeFrameHeightAndWidth();
    window.onresize = function() {
        changeFrameHeightAndWidth(); 
    }
</script>
</body>
</html>`;
}

// 假设的encodeHTML函数，用于编码HTML字符
// 实际中应使用成熟的库函数，如DOMPurify等来处理
function encodeHTML(str: string): string {
  return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
